import api from '@/store/api';
import { sortBy } from 'lodash';

export const useFanSpeedStore = defineStore('fanSpeed', () => {
  const fanSpeeds = ref({} as { [index: string]: number });
  const pwmValues = ref({} as { [index: string]: number });
  const zoneInfos = ref({} as { [index: string]: any });

  const setFanSpeeds = (Speeds: any) => {
    fanSpeeds.value = Speeds;
  };
  const setZoneInfo = (zone: any) => {
    zoneInfos.value = zone;
  };
  const setPwmValues = (allPwmValues: any) => {
    pwmValues.value = allPwmValues;
  };

  const getFanAllData = async () => {
    return api
      .get('/redfish/v1/Managers/bmc/oem/phosphor-fan-control')
      .then(({ data: { PwmInfo, TachInfo, ZoneInfo } }) => {
        ZoneInfo = sortBy(ZoneInfo, (item: { ZoneID: number }) => item.ZoneID);
        setZoneInfo(ZoneInfo);
        setPwmValues(PwmInfo);
        setFanSpeeds(TachInfo);
      })
      .catch((err) => {
        return err;
      });
  };
  const manualControl = async ({
    zoneInfo,
    pwmValues,
  }: {
    zoneInfo: { [index: string]: any };
    pwmValues: { [index: string]: any };
  }) => {
    const ZoneInfo = {
      ZoneInfo: [{ Current: zoneInfo.Current, ZoneID: zoneInfo.ZoneID }],
    };
    const PwmInfo = { PwmInfo: {} as any };
    if (zoneInfo.Current == zoneInfo.Supported[0]) {
      Object.keys(zoneInfo.FanInfo).forEach((pwmName) => {
        PwmInfo.PwmInfo[pwmName] = pwmValues[pwmName];
      });
    }
    const payload = {};
    Object.assign(payload, ZoneInfo, PwmInfo);
    return await api
      .patch('/redfish/v1/Managers/bmc/oem/phosphor-fan-control', payload)
      .catch((err) => {
        throw err;
      });
  };

  return {
    fanSpeeds,
    pwmValues,
    zoneInfos,
    setFanSpeeds,
    setZoneInfo,
    setPwmValues,
    getFanAllData,
    manualControl,
  };
});
